import { _decorator, Component, Node } from 'cc';
import { reactive, ref } from '../../reactivity';
const { ccclass, property } = _decorator;

/**
 * Model基类 - MVVM架构中的数据模型
 * 负责管理业务数据和数据持久化
 */
@ccclass('core_model')
export class core_model extends Component {
    // 响应式数据存储
    protected _data: Record<string, any> = {};
    
    // 数据变更监听器
    protected _listeners: Map<string, Function[]> = new Map();
    
    // 是否已初始化
    protected _initialized: boolean = false;
    
    start() {
        this.initialize();
    }

    update(deltaTime: number) {
        // 子类可以重写
    }
    
    /**
     * 初始化Model
     */
    protected initialize(): void {
        if (this._initialized) {
            return;
        }
        
        this._data = reactive({});
        this.initializeData();
        this._initialized = true;
        this.onInitialize();
    }
    
    /**
     * 初始化数据
     * 子类需要重写此方法来定义数据属性
     */
    protected initializeData(): void {
        // 子类需要重写
    }
    
    /**
     * 初始化完成后的回调
     */
    protected onInitialize(): void {
        // 子类可以重写
    }
    
    /**
     * 获取数据
     */
    public getData<T = any>(key: string): T {
        return this._data[key];
    }
    
    /**
     * 设置数据
     */
    public setData<T = any>(key: string, value: T): void {
        const oldValue = this._data[key];
        this._data[key] = value;
        this.notifyDataChange(key, value, oldValue);
    }
    
    /**
     * 批量设置数据
     */
    public setDataBatch(data: Record<string, any>): void {
        const changes: Array<{key: string, newValue: any, oldValue: any}> = [];
        
        for (const [key, value] of Object.entries(data)) {
            const oldValue = this._data[key];
            this._data[key] = value;
            changes.push({ key, newValue: value, oldValue });
        }
        
        // 批量通知变更
        changes.forEach(change => {
            this.notifyDataChange(change.key, change.newValue, change.oldValue);
        });
    }
    
    /**
     * 添加数据变更监听器
     */
    public addDataListener(key: string, listener: Function): void {
        if (!this._listeners.has(key)) {
            this._listeners.set(key, []);
        }
        this._listeners.get(key)!.push(listener);
    }
    
    /**
     * 移除数据变更监听器
     */
    public removeDataListener(key: string, listener: Function): void {
        const listeners = this._listeners.get(key);
        if (listeners) {
            const index = listeners.indexOf(listener);
            if (index > -1) {
                listeners.splice(index, 1);
            }
        }
    }
    
    /**
     * 通知数据变更
     */
    protected notifyDataChange(key: string, newValue: any, oldValue: any): void {
        const listeners = this._listeners.get(key);
        if (listeners) {
            listeners.forEach(listener => {
                try {
                    listener(newValue, oldValue, key);
                } catch (error) {
                    console.error(`Error in data listener for key "${key}":`, error);
                }
            });
        }
    }
    
    /**
     * 获取所有数据
     */
    public getAllData(): Record<string, any> {
        return { ...this._data };
    }
    
    /**
     * 重置数据
     */
    public resetData(): void {
        this._data = reactive({});
        this.initializeData();
    }
    
    /**
     * 检查是否已初始化
     */
    public isInitialized(): boolean {
        return this._initialized;
    }
    
    /**
     * 销毁Model
     */
    onDestroy(): void {
        this._listeners.clear();
        this._initialized = false;
    }
}


